import * as vscode from 'vscode';

class TomcatUtils{
    startMap: {[key: string]: vscode.DebugSession} = {};
    startDebugEvent: vscode.Disposable;
    stopDebugEvent: vscode.Disposable;
    constructor(){
         this.startDebugEvent = vscode.debug.onDidStartDebugSession(session => {
            this.startMap[session.name] = session;
        });
        this.stopDebugEvent = vscode.debug.onDidTerminateDebugSession((session)=>{
            delete this.startMap[session.name];
        });
    }


    /**启动调试 */
    async startTomcat(name: string, installPath: string|undefined = undefined, developPath: string|undefined = undefined, javaExec: string|undefined = undefined){
        /** 如果未配置调试目录则使用默认目录 */
        developPath = developPath === undefined ? installPath : developPath;

        let projectName = await vscode.commands.executeCommand('tomcat-hot.showProject', {});
        let debug =  {
            type: `java`,
            name: `${name}`,
            request: `launch`,
            mainClass: `org.apache.catalina.startup.Bootstrap`,
            projectName: `${projectName??""}`,
            classPaths: [
                `${installPath}\\bin\\bootstrap.jar`,
                `${installPath}\\bin\\tomcat-juli.jar`
            ],
            vmArgs: [
                `-Djava.util.logging.config.file=${installPath}\\conf\\logging.properties`,
                `-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager`,
                `-Djdk.tls.ephemeralDHKeySize=2048`,
                `-Djava.protocol.handler.pkgs=org.apache.catalina.webresources`,
                `-Dignore.endorsed.dirs=`,
                `-Dcatalina.base=${developPath}`,
                `-Dcatalina.home=${installPath}`,
                `-Djava.io.tmpdir=${developPath}\\temp`,
            ],
            args: "start",
            javaExec: `${javaExec??""}`,
            encoding: "UTF-8",
            env: {
                LANG: 'en_US.UTF - 8',
                LC_ALL: 'en_US.UTF - 8'
            }
        };
        vscode.debug.startDebugging(vscode.workspace.workspaceFolders![0], debug, {
            consoleMode: vscode.DebugConsoleMode.Separate,
            compact: true,
        });   
    }

    // 停止调试
    stopTomcat(name: string){
        if(this.startMap[name]){
            vscode.debug.stopDebugging(this.startMap[name]);
        }
    }
}



const tomcatUtils = new TomcatUtils();

export {
    tomcatUtils
};

